import { ref, reactive } from "vue"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { removeToken, setToken, getToken } from "@/utils/storage/cookies"
import { getUserInfo } from "@/api/user"
import { loginApi } from "@/api/login"
import { resetRouter } from "@/utils"
import { type ILoginRequestData } from "@/api/login/types/login"

export const useUserStore = defineStore("user", () => {
  const roles = ref<string[]>([])
  const user = reactive<any>({})
  const tagsViewStore = useTagsViewStore()

  // 登录
  const login = async (form: ILoginRequestData) => {
    return new Promise(async (resolve) => {
      // 模拟登录
      // setToken("token")
      // resolve(true)

      loginApi(form).then(async (res) => {
        setToken(res.data.token)
        resolve(true)
      })
    })
  }
  // 获取用户详情
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      // 模拟获取用户信息
      // Object.assign(user, {
      //   name: "daheishuai",
      //   nickName: "大黑帅",
      //   avatar: "https://avatars.githubusercontent.com/u/20457624?s=460&u=2c3e8f9d5f43e9f43f9fcaaadf4e88d4d8b8e5d4&v=4",
      // })
      // roles.value = ["admin"]
      // resolve(user)
      getUserInfo()
        .then(async (res: any) => {
          // 用户信息
          // Object.assign(user, res.data.user)
          Object.assign(user, res.data)
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // 登出
  const logout = () => {
    roles.value = []
    removeToken()
    resetRouter()
    resetTagsView()
  }
  // 重置 visited views 和 cached views
  const resetTagsView = () => {
    tagsViewStore.delAllVisitedViews()
    tagsViewStore.delAllCachedViews()
  }

  return { user, roles, login, getInfo, logout }
})
